<template>
  <VPdf ref="pdfRef" id="printPay" :title="form.template_name" width="1280px">
    <component v-if="load" :is="com" v-model="form" :isLook="isLook" :edit="!isLook" @load="handleLoad" />
    <template v-if="!isLook" #footer>
      <el-button @click="pdfRef.close()">取 消</el-button>
      <el-button type="primary" :loading="loading" class="ml-3" @click="submit">保 存</el-button>
    </template>
  </VPdf>
</template>

<script setup>
import api from '../../api'
import Template1 from './Template1'
import Template2 from './Template2'
import Template3 from './Template3'
import Template5 from './Template5'
import VPdf from '@/components/VPdf'
import { urlToBase64 } from '@/utils'
import { ElMessage } from 'element-plus'
import XEUtils from 'xe-utils'
// import { getLodop } from '@/utils/LodopFuncs'
// import html2canvas from 'html2canvas'

const emit = defineEmits('end', 'success')

const type = ref(2)
const com = computed(() => ['', Template1, Template2, Template3, '', Template5][type.value])
const load = ref(false)
const loading = ref(false)

const form = ref({})
const getForm = async (row) => {
  const { c_id, doc_type } = row
  type.value = doc_type
  load.value = false
  const res = await api.printDetail({ c_id })
  try {
    if (doc_type < 3) {
      const toBase64 = res.data.value[doc_type === 1 ? 'purchase_info' : 'plan_info'].map(async d => {
        if (d.main_img) {
          d.base64 = await urlToBase64(d.main_img)
        }
        return d
      })
      await Promise.all(toBase64)
    }
  } catch (error) {
    console.error(error)
  }

  form.value = res.data
  load.value = true
  await nextTick()
}
const pdfRef = ref()
const data = ref([])
const next = async () => {
  const row = data.value.shift()
  try {
    await getForm(row)
    const { template_name, supplier_name, contract_type_name } = form.value
    await pdfRef?.value.open(`${template_name}-${contract_type_name}-${supplier_name}-${XEUtils.toDateString(Date.now(), 'yyyyMMdd')}`)
  } catch (error) {
    console.log('error', error)
  }
}

const isLook = ref(false)
const pdf = async (rows, opts) => {
  data.value = Array.isArray(rows) ? rows : [rows]
  isLook.value = opts.isLook
  await nextTick()
  await next()
  opts.closeLoading()
}

const isView = ref(false)
const view = async (rows, opts) => {
  data.value = Array.isArray(rows) ? rows : [rows]
  isView.value = true
  isLook.value = true
  await nextTick()
  await next()
  opts.closeLoading()
}

// const _createCanvas = async function (el, noClass) {
//   return html2canvas(el, {
//       backgroundColor: '#ffffff',
//       allowTaint: false,
//       useCORS: true,
//       ignoreElements: (element) => {
//           for (let i = 0, len = noClass.length; i < len; ++i) {
//               if ([].includes.call(element.classList, noClass[i])) {
//                   return true;
//               }
//           }
//       }
//   })
// }

const handleLoad = async () => {
  // const LODOP = getLodop()
  // if(!LODOP) {
  //   const canvas = await _createCanvas(pdfRef?.value.elRef, ["no2canvas"])
  //   let dataURL = await canvas.toDataURL('image/jpeg', 1.0)
  //   LODOP.SET_PRINT_PAGESIZE(1, 0, 0, "A4")
  //   LODOP.SET_PRINT_MODE("PRINT_PAGE_PERCENT",'Full-Width')
  //   LODOP.NEWPAGEA()
  //   const html = `
  //     <div style='width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;'>
  //       <img src="${dataURL}" style='width: 100%;height: auto;max-width: 100%;max-height:100%' />
  //     </div>
  //     `
  //   LODOP.ADD_PRINT_HTM(20, 20, '210mm', '280mm', html)
  //   LODOP.PREVIEW()
  // } else {
  //   await pdfRef?.value.start()
  // }
  if(isView.value) return
  await pdfRef?.value.start()
  if (data.value.length) {
    await next()
  } else {
    pdfRef?.value.close()
  }
}

const submit = async () => {
  loading.value = true
  const params = XEUtils.clone(form.value, true)
  if (type.value < 3) {
    params.value[type.value === 1 ? 'purchase_info' : 'plan_info'].forEach(d => {
      d.base64 = null
    })
  }
  api.updateContract(params).then(res => {
    ElMessage.success('操作成功')
    emit('success')
  }).finally(() => {
    loading.value = false
    pdfRef?.value.close()
  })
}

defineExpose({ pdf, view })
</script>